using Godot;
using System;
using System.Collections.Generic;

namespace PlayerWeapon
{
public partial class Weapon : Node2D
{
	public AnimatedSprite2D up,down,left,right;

	public Enemy enemy;

	public Timer timer;

	public AudioStreamPlayer2D audioStreamPlayer2D;

	public List<AudioStream> audioStreams;

	public override void _Ready()
	{
		up = GetNode<AnimatedSprite2D>("Up");
		down = GetNode<AnimatedSprite2D>("Down");
		left = GetNode<AnimatedSprite2D>("Left");
		right = GetNode<AnimatedSprite2D>("Right");

		enemy = GetNode<Enemy>("/root/Main/Enemy");

		audioStreamPlayer2D = GetNode<AudioStreamPlayer2D>("Music");

		audioStreams = new(){
			ResourceLoader.Load<AudioStream>("res://resources/audio/player_attack_1.mp3"),
			ResourceLoader.Load<AudioStream>("res://resources/audio/player_attack_2.mp3"),
			ResourceLoader.Load<AudioStream>("res://resources/audio/player_attack_3.mp3")
		};

		List<AnimatedSprite2D> temps = new()
        {
			up,
			down,
			left,
			right
		};

		foreach(var e in temps)
		{
			e.AnimationFinished+=()=>OnAttackFinished(e);

			e.GetNode<Area2D>("Area2D").BodyEntered+=OnCollision;
		}
	}

	public void OnCollision(Node2D body)
	{
		if(body.Name=="Enemy")
		{
			enemy.OnHurt();
		}
	}

	public void OnAttackFinished(AnimatedSprite2D anima)
	{
		audioStreamPlayer2D.Stop();
		anima.Visible = false;
		anima.GetNode<Area2D>("Area2D").SetCollisionMaskValue(3,false);
	}

	public void OnAttack(AnimatedSprite2D anima)
	{
		audioStreamPlayer2D.Stream = audioStreams[(int)MyUtil.RangeRandom(0,3)];
		audioStreamPlayer2D.Play();

		anima.Visible = true;
		anima.GetNode<Area2D>("Area2D").SetCollisionMaskValue(3,true);
		anima.Play();
	}
}
}
